<template>
  <!-- 页面-资源管理 -->
  <div class="padding-20 page-box-row-left innerPageTable-box-OneTwo">
    <FormBlock :title="$t('module.resourceManage.resList')" direction="column" style="width:280px">
      <el-tree
        :data="baseData"
        :props="defaultProps"
        highlight-current
        check-strictly
        :indent="10"
        node-key="id"
        ref="functionTree"
        icon-class="ivu-icon-ios-arrow-forward"
        @node-click="handleNodeClick"
        :expand-on-click-node="true"
        :load="loadNode"
        lazy
      >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <Tooltip :content="$t('common.frozen')" :disabled="data.enabled != 0" placement="top">
            <span :class="data.enabled == 0?'invalidStyle':''">
              <Icon type="ios-bulb" v-if="data.functionType == '2'" />
              <Icon type="md-menu" v-if="data.functionType == '1'" />
              <Icon type="ios-ionic-outline" v-if="data.functionType == '0'" />
              <Icon type="md-home" v-if="data.resourceType == '1' || data.resourceType == '3'"></Icon>
              <Icon type="md-cloud-outline" v-if="data.resourceType == '2'"></Icon>
              <Icon type="md-cloud" v-if="data.isPublicAPI"></Icon>
              {{ node.label }}
            </span>
          </Tooltip>
        </span>
      </el-tree>
    </FormBlock>
    <FormBlock :title="title" direction="column">
      <!-- 搜索区域 -->
      <SelfAdaption>
        <Form
          :model="searchForm"
          ref="resourceForm"
          slot="adaption-bar"
          label-position="top"
          class="ivu-form-no-margin-bottom"
          inline
        >
          <template>
            <!-- 资源编码 -->
            <Form-item prop="resourceCode" :label="$t('module.resourceManage.resCode')">
              <Input
                type="text"
                :maxlength="30"
                v-model.trim="searchForm.resourceCode"
                placeholder
                
                @on-enter="search"
              ></Input>
            </Form-item>

            <!-- 资源名称 -->
            <Form-item prop="resourceName" :label="$t('module.resourceManage.resName')">
              <Input
                type="text"
                :maxlength="30"
                v-model.trim="searchForm.resourceName"
                placeholder
                
                @on-enter="search"
              ></Input>
            </Form-item>

            <!-- 查询\重置按钮 -->
            <Form-item prop="button" class="search-solt-btn">
              <RPButton optType="search" @click="search" />
              <RPButton optType="reset" @click="reset" />
            </Form-item>
          </template>
        </Form>
      </SelfAdaption>
      <InnerPageTable ref="resourceTable" :config="tableConfig">
        <!-- handler bar 查询/重置-->
        <!--
        <div slot="handle-bar">
          <RPButton optType="search" @click="search" />
          <RPButton optType="reset" @click="reset" />
        </div>
        -->
        <!-- table bar 添加-->
        <div slot="table-bar">
          <RPButton :disabled="isButtonDisabled" optType="create" @click="add" />
          <RPButton
            :disabled="isButtonDisabled && isDeleteDisabled"
            optType="delete"
            @click="deleted"
          />
        </div>
      </InnerPageTable>
    </FormBlock>
  </div>
</template>
<script>
import ResourceEdit from "./ResourceEdit.vue";
import CopyResource from "./CopyResource.vue";
import { queryResouceList, deleteByIdAndParentId, queryResouceTree } from "@/api/resourceApi.js";
import { searchAppList } from "@/api/applicationApi.js";
import { getRolePostId } from "@/api/postApi.js";
import functionAPI from "@/api/functionAPI.js";
import { mrmColumns } from "./columns.js";
import { CoreModuleName } from "@/const.js";
import locales from "./locales.js";

export default {
  name: "function-resource",
  mixins: [locales],
  data() {
    return {
      // resourceTitle: this.$t("module.resourceManage.resAddresListMaxFifty"),
      modal: false,
      noData: false,
      showDetail: false,
      firstLoading: true,
      searchForm: {
        applicationId: "",
        functionId: "",
        parentResourceId: "",
        resourceCode: "",
        resourceName: "",
        publicFlag: null
      },
      // resourceType: ["UI资源", "API资源", "功能权限"],
      baseData: [],
      selectedData: {},
      selectedMenuID: "",
      selectedMenuName: "",
      defaultProps: {
        children: "children",
        label: "functionName"
      },
      node: {},
      nodeElement: {},
      title: "",
      isButtonDisabled: true,
      isDeleteDisabled: true,
      canCreateUI: true,
      canCreateAPI: true,
      canCreateFunc: true,
      isOnlyPublic: false,
      appList: [],
      isShowCode:true
    }
    
    
  },
  computed: {
    tableConfig() {
      return {
        loadDataFn: ({ responseProcess, param }) => {
          queryResouceList(param).then(res => {
            // 状态为有效：禁用复选框，不可删除
            let { records } = res;
            console.log(records)
            records = this.$root.$options.filters["selection-disabled"](records);
            responseProcess(res);
          });
        },
        columnsFn: mrmColumns.bind(this),
        initParam: this.searchForm,
        autoFirst: true
      };
    },
    resourceType() {
      return [
        this.$t("module.resourceManage.uiResource"),
        this.$t("module.resourceManage.apiResource"),
        this.$t("module.resourceManage.functionalAuthority")
      ];
    }
  },
  created: function() {
    // 查询应用
    this.initApplication();
  },
  updated: function() {
    //默认显示第一个部门信息
    if (this.firstLoading && this.baseData.length > 0) {
      this.$refs["functionTree"].setCurrentKey(this.baseData[0].id);
      this.selectedMenuID = this.baseData[0].id;
      this.selectedMenuName = this.baseData[0].functionName;
      this.title = this.selectedMenuName;
      this.updateResourceTitle(this.selectedMenuName);
      this.searchForm.functionId = this.baseData[0].id; //查询参数
      this.firstLoading = false;
      // debugger
      //刷新列表
      // this.refresh();
    }
  },
  methods: {
    search(data) {
      //刷新列表
      this.$refs["resourceTable"].load(this.searchForm);
    },
    reset() {
      this.$refs["resourceForm"].resetFields();
      this.search();
    },
    updateResourceTitle(title) {
      this.resourceTitle = `${title} / ${this.$t("module.resourceManage.resList")}`;
    },
    handleNodeClick(data, node, nodeElement) {
      this.node = node;
      this.isOnlyPublic = false;
      this.isDeleteDisabled = true;
      this.$refs["resourceForm"].resetFields();
      if (data.functionType && data.functionType == "2") {
        // 节点是应用
        // 应用下不能添加资源
        this.isButtonDisabled = true;
        this.isDeleteDisabled = false;
        // 查询参数
        this.searchForm.applicationId = data.applicationId;
        // debugger
        this.searchForm.functionId = null;
        this.searchForm.parentResourceId = null;
        this.searchForm.publicFlag = null;
        // 刷新列表
        this.search();
      } else if (data.functionType && data.functionType == "0") {
        // 节点是菜单
        this.isButtonDisabled = false;
        this.canCreateUI = true;
        this.canCreateAPI = false;
        this.canCreateFunc = true;
        // 查询参数
        this.searchForm.applicationId = data.applicationId;
        // debugger
        this.searchForm.functionId = data.id;
        this.searchForm.parentResourceId = null;
        this.searchForm.publicFlag = null;
        // 刷新列表
        this.search();

        this.updateResourceTitle(data.title);
        this.selectedMenuID = data.id;
      } else if (data.resourceType) {
        // 节点是资源
        this.isButtonDisabled = data.resourceType == 3;
        // 只有UI资源下能新增UI资源
        this.canCreateUI = data.resourceType == 1;
        this.canCreateAPI = data.resourceType != 3;
        this.canCreateFunc = false;
        //查询参数
        this.searchForm.applicationId = data.applicationId;
        // debugger
        this.searchForm.functionId = null;
        this.searchForm.parentResourceId = data.id;
        this.searchForm.publicFlag = null;
        //刷新列表
        this.search();

        this.selectedMenuID = data.functionId;
      } else if (data.isPublicAPI) {
        // 节点是公共API
        this.isButtonDisabled = false;
        this.canCreateUI = false;
        this.canCreateAPI = true;
        this.canCreateFunc = false;
        this.isOnlyPublic = true;
        //查询参数
        this.searchForm.applicationId = data.applicationId;
        this.searchForm.functionId = null;
        this.searchForm.parentResourceId = null;
        this.searchForm.publicFlag = 1;
        //刷新列表
        this.search();
      } else {
        // 功能目录不能添加资源
        this.isButtonDisabled = true;
        //刷新列表
        this.$refs["resourceTable"].tableData = [];
        this.$refs["resourceTable"].total = 0;
        this.$refs["resourceTable"].param.pageNum = 1;
      }
      this.title = data.functionName;
    },
    add() {
      const applicationId = this.node.data.applicationId;
      const { appList } = this;
      // 当前应用
      const currentApplication = appList.find(app => app.clientId === applicationId) || {};
      new this.$pageModal(
        ResourceEdit,
        {
          props: {
            functionId: this.selectedMenuID,
            parentResourceId: this.searchForm.parentResourceId,
            applicationId,
            applicationName: currentApplication.appName || "",
            canCreateUI: this.canCreateUI,
            canCreateAPI: this.canCreateAPI,
            canCreateFunc: this.canCreateFunc,
            isOnlyPublic: this.isOnlyPublic
          }
        },
        data => {
          if (data) {
            // 刷新树
            data.functionName = data.resourceName;
            data.children = [];
            this.node.store.append(data, this.node.data);
            this.search();
          }
        }
      );
    },
    edit(row) {
      const { appList } = this;
      // 当前应用
      const currentApplication = appList.find(app => app.clientId === row.applicationId) || {};
      new this.$pageModal(
        ResourceEdit,
        {
          props: {
            id: row.id,
            functionId: this.selectedMenuID,
            applicationId: row.applicationId,
            applicationName: currentApplication.appName || "",
            resourceObj: row,
            canCreateUI: this.canCreateUI,
            canCreateAPI: this.canCreateAPI,
            canCreateFunc: this.canCreateFunc,
            isOnlyPublic: this.isOnlyPublic,
            isShowCode:this.isShowCode
          }
        },
        data => {
          if (data) {
            this.search();
          }
        }
      );
    },
    copy() {
      new this.$pageModal(
        CopyResource,
        {
          props: {
            functionId: this.selectedMenuID,
            parentResourceId: this.searchForm.parentResourceId,
            // applicationId: this.node.data.applicationId ? this.node.data.applicationId : this.node.data.applicationId,
            canCreateUI: this.canCreateUI,
            canCreateAPI: this.canCreateAPI,
            canCreateFunc: this.canCreateFunc,
            isOnlyPublic: this.isOnlyPublic
          }
        },
        data => {
          if (data) {
            this.search();
          }
        }
      );
    },
    deleted() {
      let selectedIds = this.getSelectedIds();
      if (selectedIds.length == 0) {
        this.$message.error({
          content: this.$t("module.resourceManage.selectDeletion"),
          duration: 3
        });
        return;
      }
      let selectedRows = this.$refs["resourceTable"].getSelectioned();
      new $confirm(this.$t("module.resourceManage.confirmDelete"), this).then(() => {
        deleteByIdAndParentId(selectedIds)
          .then(response => {
            this.$message.success({
              content: this.$t("module.orgManage.deleteSuccess"),
              duration: 3
            });
            this.search();
            // this.removeRow(selectedRows);
            this.removeNode(this.node.store, selectedRows);
          })
          .catch(data => {
            this.$message.error({
              content: data.message,
              duration: 3
            });
          });
      });
    },
    getSelectedIds() {
      let list = this.$refs["resourceTable"].getSelectioned() || [];
      let ids = [];
      for (let u of list) {
        ids.push({ id: u.id, parentResourceId: u.parentResourceId });
      }
      return ids;
    },
    initApplication() {
      // 当前岗位
      const { currentPost } = $store.state[CoreModuleName];

      // 增加无应用根节点
      this.createPublicNode();

      // 获取应用
      searchAppList({ pageNum: 1, pageSize: 200 }).then(({ data: { records } }) => {
        this.appList = records;

        for (let index = 0; index < records.length; index++) {
          const application = records[index];
          this.baseData.push({
            applicationId: application.clientId,
            functionName: application.appName,
            id: index,
            menuCode: index,
            menuDesc: this.$t("module.functionManage.topMenu"),
            parentMenuName: this.$t("module.functionManage.nothing"),
            sort: "0",
            actionUrl: this.$t("module.functionManage.nothing"),
            functionType: "2",
            children: [], //后天调取的树中的data放在这里
            enabled: application.enabled
          });
          // 初始化菜单
          this.initMenus(this.baseData.length - 1, application.clientId);
        }
      });
    },
    initMenus(index, appId) {
      functionAPI.queryFunctionList(appId).then(data => {
        this.baseData[index].children = data;
        let publicAPI = {
          applicationId: appId,
          id: index,
          functionName: "公共API",
          children: [],
          isPublicAPI: true
        };
        this.baseData[index].children.push(publicAPI);
      });
    },
    loadNode(node, resolve) {
      // console.log("functionType=" + node.data.functionType);
      // console.log("functionName=" + node.data.functionName);
      // debugger;
      // if (node.data.children && node.data.children.length > 0) {
      //   resolve(node.data.children);
      // }
      //
      if (node.level == 0) {
        // 隐藏根节点
        return;
      }

      if (node.data.functionType == "1") {
        // 节点是菜单目录
        resolve(node.data.children);
      } else if (node.data.functionType == "0") {
        // 节点是菜单
        this.loadResource(node.data, resolve);
      } else if (node.data.resourceType) {
        // 节点是资源
        node.data.children.forEach(resource => {
          resource.functionName = resource.resourceName;
        });
        resolve(node.data.children);
      } else {
        // 未知类型节点
        resolve(node.data.children);
      }
    },
    loadResource(parentNode, resolve) {
      let param = { functionId: parentNode.id };
      // this.$store
      //   .dispatch("QueryResouceTree", param)
      queryResouceTree(param)
        .then(res => {
          const { data } = res;
          data.forEach(resource => {
            parentNode.children.push(resource);
            resource.functionName = resource.resourceName;
          });
          resolve(data);
        })
        .catch(data => {
          this.$message.error({
            content: data.message,
            duration: 3
          });
        });
    },
    removeNode(store, datas) {
      datas.forEach(data => {
        store.remove(data);
      });
    },
    removeRow(selectedRows) {
      selectedRows.forEach(resource => {
        let allRows = this.$refs["resourceTable"].tableData;
        for (let index = 0; index < allRows.length; index++) {
          const row = allRows[index];
          if (resource.id == row.id) {
            // 从列表删除选中行
            // this.$refs["resourceTable"].tableData.splice(index, 1);
            this.$refs["resourceTable"].selectAll(false);
            continue;
          }
        }
      });
    },
    // 增加无应用根节点
    createPublicNode() {
      let rootNode = {
        applicationId: "",
        functionName: this.$t("module.resourceManage.publicFunction"),
        id: "public",
        menuCode: "PUBLIC",
        menuDesc: this.$t("module.functionManage.topMenu"),
        parentMenuName: this.$t("module.functionManage.nothing"),
        sort: "0",
        actionUrl: this.$t("module.functionManage.nothing"),
        functionType: "2",
        children: [] //后天调取的树中的data放在这里
      };
      this.baseData.push(rootNode);
      // this.loadNode("", rootNode); //初始化加载
      // 初始化菜单
      this.initMenus(0, "");
    }
  }
};
</script>
<style lang="less">
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 12px;
  padding-right: 8px;
}
</style>

